// app.js
App({
  globalData: {
    userInfo: null,
    userType: null, // 'student' 或 'judge'
    baseUrl: "http://localhost:3000/api",
  },

  onLaunch() {
    // 初始化云开发
    if (!wx.cloud) {
      console.error("请使用 2.2.3 或以上的基础库以使用云能力");
    } else {
      wx.cloud.init({
        env: "cloud1-8ge4r07b19630764", // 替换为你的云环境ID
        traceUser: true,
      });
    }

    // 检查登录状态
    this.checkLoginStatus();
  },

  // 自定义 tabBar 相关方法
  onShow() {
    // 更新自定义 tabBar 的选中状态
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: this.getCurrentTabIndex(),
      });
    }
  },

  getCurrentTabIndex() {
    const pages = getCurrentPages();
    if (pages.length === 0) {
      return 0;
    }

    const currentPage = pages[pages.length - 1];
    if (!currentPage || !currentPage.route) {
      return 0;
    }

    const route = currentPage.route;
    const tabList = [
      "pages/student/profile/profile",
      "pages/student/transcript/transcript",
      "pages/student/research/research",
      "pages/student/application/application",
    ];

    return tabList.indexOf(route);
  },

  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    const userType = wx.getStorageSync("userType");

    if (token && userType) {
      this.globalData.userType = userType;
      // 验证token有效性
      this.validateToken(token);
    }
  },

  validateToken(token) {
    // 本地模式：不再请求后端，直接从本地恢复用户信息
    try {
      const storedUser = wx.getStorageSync("userInfo");
      if (storedUser) {
        this.globalData.userInfo = storedUser;
        return;
      }
    } catch (_) {}
    this.logout();
  },

  login(userInfo, userType) {
    this.globalData.userInfo = userInfo;
    this.globalData.userType = userType;
    wx.setStorageSync("userInfo", userInfo);
    wx.setStorageSync("userType", userType);
  },

  logout() {
    this.globalData.userInfo = null;
    this.globalData.userType = null;
    wx.removeStorageSync("userInfo");
    wx.removeStorageSync("userType");
    wx.removeStorageSync("token");
    wx.reLaunch({
      url: "/pages/index/index",
    });
  },
});
